package com.bolt.core.view.components;

import com.bolt.common.ognl.ExpressionUtil;
import com.bolt.common.web.RequestUtil;
import com.bolt.common.utils.SpringContextUtil;
import com.bolt.common.utils.StrUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;
import java.util.Map;


public class SelectBase extends FormItem {

	private static final String FROM_LIST = "loader";
	
	@Override
    protected void evaluateValue(HttpServletRequest request) {
		super.evaluateValue(request);
		Object loader = null;
        if(parameters.get(FROM_LIST)!=null){
    		 loader = SpringContextUtil.getBean((String)this.parameters.get(FROM_LIST) );
        }	
		if(loader!=null){
			ListDataLoad load = (ListDataLoad)loader;
			Map<String,String> values = load.load(this, RequestUtil.getQueryParams(request));
            request.setAttribute("itemValue", values);
		}
	}

    @Override
	protected void evaluateParams(HttpServletRequest req){
        super.evaluateParams(req);
        if ( parameters.containsKey("refUrl") ) {
            String url = (String) parameters.get("refUrl");
            if(ExpressionUtil.containsExpression(url)){
                String refUrl = (String) parameters.get("refUrl");
                String newValue = ExpressionUtil.parseText(refUrl,  RequestUtil.getQueryParams(req));
                req.setAttribute("refUrl", StrUtil.trim(newValue));
            }

        }
    }
	
	@Override
	public void end(HttpServletRequest request, HttpServletResponse response, Writer writer) {
		super.end(request,response,writer);
        request.removeAttribute("itemValue");
        request.removeAttribute("refUrl");
	}
	

}
